package com.white.controller;

import com.white.upload.Upload;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;

@Slf4j
@Controller
public class UploadController {

    @GetMapping("upload.html")
    public String upload() {
        return "upload";
    }
    @PostMapping("upload")
    public String upload(HttpServletRequest request,
                         @RequestParam("name") String name,
                         @RequestParam("email") String email,
                         @RequestPart("headImg") MultipartFile headImg,
                         @RequestPart("liveImgs") MultipartFile[] liveImgs) throws IOException {
        /*保存数据*/
        log.info("姓名：{}，邮箱：{}，头像大小：{}，生活照数量：{}",
                name, email, headImg.getSize(), liveImgs.length);
        /*将图片进行保存*/
        String path = "E:\\图片\\";
        String realpath = request.getServletContext().getRealPath("/");
        log.info("真实路径：{}", realpath);
        if (!headImg.isEmpty()) {
            headImg.transferTo(new File(path + headImg.getOriginalFilename()));
        }
        if (liveImgs.length > 0) {
            for (MultipartFile liveImg : liveImgs) {
                if (!liveImg.isEmpty()) {
                    liveImg.transferTo(new File(path + liveImg.getOriginalFilename()));
                }
            }
        }
        return "redirect:home.html";
    }

    @PostMapping("/uploadImage")
    @ResponseBody
    public void uploadImage(@RequestPart("headImage") MultipartFile multipartFile) {
        Upload upload = new Upload();
        upload.upload(multipartFile);
    }


    /**
     * 图片上传
     * @param multipartFile
     * @return
     */
    @PostMapping("/uploadImages")
    @ResponseBody
    public Object uploadImages(@RequestPart("upload") MultipartFile multipartFile) {
        HashMap<String, Object> ans = new HashMap<>();
        Upload upload = new Upload();
        ans.put("uploaded", upload.upload(multipartFile));
        ans.put("url", "/upload/images/" + multipartFile.getOriginalFilename());
        return ans;
    }


}
